<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="垃圾投放记录修改系统">
    <title>修改垃圾投放记录</title>
    <style>
        :root {
            --primary-color: #007BFF;
            --primary-hover: #0056b3;
            --error-color: #dc3545;
            --success-color: #28a745;
            --border-color: #ddd;
            --even-row: #f2f2f2;
            --hover-row: #e0e0e0;
        }

        body {
            font-family: 'Arial', sans-serif;
            background-color: #f4f4f4;
            margin: 0;
            padding: 0;
            color: #333;
            line-height: 1.6;
        }

        .container {
            max-width: 1200px;
            margin: 20px auto;
            padding: 20px;
            background-color: #fff;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            border-radius: 8px;
        }

        h1 {
            text-align: center;
            color: var(--primary-color);
            margin-bottom: 20px;
        }

        .query-container {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            align-items: center;
            margin-bottom: 20px;
        }

        label {
            font-weight: bold;
            margin-right: 5px;
        }

        input, select {
            padding: 8px 12px;
            border: 1px solid var(--border-color);
            border-radius: 4px;
            font-size: 16px;
        }

        button {
            padding: 10px 20px;
            background-color: var(--primary-color);
            color: #fff;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            transition: background-color 0.3s;
        }

        button:hover {
            background-color: var(--primary-hover);
        }

        .message {
            text-align: center;
            margin: 10px 0;
            padding: 10px;
            border-radius: 4px;
            display: none;
        }

        .error {
            background-color: #f8d7da;
            color: var(--error-color);
            border: 1px solid #f5c6cb;
        }

        .success {
            background-color: #d4edda;
            color: var(--success-color);
            border: 1px solid #c3e6cb;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.05);
        }

        th, td {
            padding: 12px;
            text-align: center;
            border: 1px solid var(--border-color);
        }

        th {
            background-color: var(--primary-color);
            color: #fff;
            font-weight: bold;
        }

        tr:nth-child(even) {
            background-color: var(--even-row);
        }

        tr:hover {
            background-color: var(--hover-row);
        }

        .form-container {
            max-width: 600px;
            margin: 20px auto;
            padding: 20px;
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }

        .form-group {
            margin-bottom: 15px;
        }

        .form-group label {
            display: block;
            margin-bottom: 5px;
        }

        .form-group input,
        .form-group select {
            width: 100%;
            box-sizing: border-box;
        }

        .loading {
            display: none;
            text-align: center;
            margin: 20px 0;
        }

        .spinner {
            border: 4px solid rgba(0, 0, 0, 0.1);
            border-radius: 50%;
            border-top: 4px solid var(--primary-color);
            width: 30px;
            height: 30px;
            animation: spin 1s linear infinite;
            margin: 0 auto;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        @media (max-width: 768px) {
            .container {
                padding: 10px;
            }

            .query-container {
                flex-direction: column;
                align-items: stretch;
            }

            table {
                font-size: 14px;
            }

            th, td {
                padding: 8px;
            }
        }
    </style>
</head>
<body>
<div class="container">
    <div class="header">
        <h1>修改垃圾投放记录</h1>
    </div>

    <div class="query-container">
        <label for="queryResidentId">请输入居民编号：</label>
        <input type="text" id="queryResidentId" name="queryResidentId" required>
        <button id="searchBtn">查询</button>
    </div>

    <div id="error-message" class="message error" role="alert"></div>
    <div id="success-message" class="message success" role="alert"></div>

    <div class="loading" id="loading">
        <div class="spinner"></div>
        <p>加载中...</p>
    </div>

    <table id="wasteRecordsTable" style="display: none;">
        <thead>
        <tr>
            <th>编号</th>
            <th>居民编号</th>
            <th>垃圾类型</th>
            <th>投放时间</th>
            <th>重量 (kg)</th>
            <th>投放地点</th>
            <th>审核状态</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody>
        <!-- 查询结果将在此处动态插入 -->
        </tbody>
    </table>

    <div class="form-container" id="updateWasteRecordForm" style="display: none;">
        <h2>修改记录</h2>
        <form id="recordForm">
            <div class="form-group">
                <label for="recordId">记录编号：</label>
                <input type="text" id="recordId" name="recordId" readonly>
            </div>

            <div class="form-group">
                <label for="formResidentId">居民编号：</label>
                <input type="text" id="formResidentId" name="formResidentId" required>
            </div>

            <div class="form-group">
                <label for="type">垃圾类型：</label>
                <select id="type" name="type" required>
                    <option value="">请选择垃圾类型</option>
                    <option value="可回收物">可回收物</option>
                    <option value="厨余垃圾">厨余垃圾</option>
                    <option value="有害垃圾">有害垃圾</option>
                    <option value="其他垃圾">其他垃圾</option>
                </select>
            </div>

            <div class="form-group">
                <label for="time">投放时间：</label>
                <input type="datetime-local" id="time" name="time" required>
            </div>

            <div class="form-group">
                <label for="weight">重量 (kg)：</label>
                <input type="number" id="weight" name="weight" step="0.1" min="0" required>
            </div>

            <div class="form-group">
                <label for="location">投放地点：</label>
                <input type="text" id="location" name="location" required>
            </div>

            <div class="form-group">
                <label for="status">审核状态：</label>
                <select id="status" name="status" required>
                    <option value="">请选择审核状态</option>
                    <option value="已审核">已审核</option>
                    <option value="待审核">待审核</option>
                </select>
            </div>

            <div class="form-group">
                <button type="submit">提交</button>
                <button type="button" id="cancelBtn">取消</button>
            </div>
        </form>
    </div>
</div>

<script>
    // 全局变量
    const apiBaseUrl = 'http://localhost:8081/waste';
    let currentRecords = [];

    // DOM元素
    const elements = {
        queryResidentId: document.getElementById('queryResidentId'),
        searchBtn: document.getElementById('searchBtn'),
        errorMessage: document.getElementById('error-message'),
        successMessage: document.getElementById('success-message'),
        loading: document.getElementById('loading'),
        wasteRecordsTable: document.getElementById('wasteRecordsTable'),
        recordForm: document.getElementById('recordForm'),
        updateWasteRecordForm: document.getElementById('updateWasteRecordForm'),
        cancelBtn: document.getElementById('cancelBtn')
    };

    // 初始化事件监听
    function initEventListeners() {
        elements.searchBtn.addEventListener('click', fetchWasteRecords);
        elements.recordForm.addEventListener('submit', handleFormSubmit);
        elements.cancelBtn.addEventListener('click', hideForm);

        // 回车键触发查询
        elements.queryResidentId.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                fetchWasteRecords();
            }
        });
    }

    // 显示消息
    function showMessage(type, message) {
        const element = type === 'error' ? elements.errorMessage : elements.successMessage;
        element.textContent = message;
        element.style.display = 'block';

        // 隐藏另一种类型的消息
        const otherElement = type === 'error' ? elements.successMessage : elements.errorMessage;
        otherElement.style.display = 'none';

        // 自动隐藏消息
        if (message) {
            setTimeout(() => {
                element.style.display = 'none';
            }, 5000);
        }
    }

    // 显示加载状态
    function showLoading(show) {
        elements.loading.style.display = show ? 'block' : 'none';
    }

    // 获取垃圾投放记录
    async function fetchWasteRecords() {
        const residentId = elements.queryResidentId.value.trim();

        if (!residentId) {
            showMessage('error', '请输入居民编号！');
            return;
        }

        try {
            showLoading(true);
            showMessage('error', '');
            showMessage('success', '');

            const response = await fetch(`${apiBaseUrl}/selectWasteRecordByResidentId?residentId=${residentId}`);

            if (!response.ok) {
                throw new Error('查询失败');
            }

            const data = await response.json();
            currentRecords = data;

            renderRecordsTable(data);
            showMessage('success', '查询成功！');
        } catch (error) {
            console.error('查询错误:', error);
            showMessage('error', '查询失败，请稍后再试！');
        } finally {
            showLoading(false);
        }
    }

    // 渲染记录表格
    function renderRecordsTable(records) {
        const tableBody = document.querySelector('#wasteRecordsTable tbody');
        tableBody.innerHTML = '';

        if (records.length === 0) {
            tableBody.innerHTML = '<tr><td colspan="8">没有找到相关记录</td></tr>';
            elements.wasteRecordsTable.style.display = 'table';
            hideForm();
            return;
        }

        records.forEach(record => {
            const row = document.createElement('tr');
            row.innerHTML = `
                <td>${record.id}</td>
                <td>${record.residentId}</td>
                <td>${record.type}</td>
                <td>${formatDateTime(record.time)}</td>
                <td>${record.weight}</td>
                <td>${record.location}</td>
                <td>${record.status}</td>
                <td><button class="edit-btn" data-id="${record.id}">修改</button></td>
            `;
            tableBody.appendChild(row);
        });

        // 添加事件委托处理修改按钮点击
        tableBody.addEventListener('click', (e) => {
            if (e.target.classList.contains('edit-btn')) {
                const recordId = e.target.getAttribute('data-id');
                selectRecord(recordId);
            }
        });

        elements.wasteRecordsTable.style.display = 'table';
    }

    // 格式化日期时间
    function formatDateTime(dateTimeString) {
        if (!dateTimeString) return '';

        const date = new Date(dateTimeString);
        if (isNaN(date.getTime())) return dateTimeString;

        return date.toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
        });
    }

    // 选择记录进行修改
    function selectRecord(recordId) {
        const record = currentRecords.find(r => r.id == recordId);

        if (!record) {
            showMessage('error', '未找到选中的记录');
            return;
        }

        // 填充表单
        document.getElementById('recordId').value = record.id;
        document.getElementById('formResidentId').value = record.residentId;
        document.getElementById('type').value = record.type;
        document.getElementById('time').value = formatDateTimeForInput(record.time);
        document.getElementById('weight').value = record.weight;
        document.getElementById('location').value = record.location;
        document.getElementById('status').value = record.status;

        // 显示表单
        elements.updateWasteRecordForm.style.display = 'block';

        // 滚动到表单
        elements.updateWasteRecordForm.scrollIntoView({ behavior: 'smooth' });
    }

    // 格式化日期时间用于input[type=datetime-local]
    function formatDateTimeForInput(dateTimeString) {
        if (!dateTimeString) return '';

        const date = new Date(dateTimeString);
        if (isNaN(date.getTime())) return dateTimeString;

        // 转换为YYYY-MM-DDTHH:MM格式
        const pad = num => num.toString().padStart(2, '0');
        return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}`;
    }

    // 隐藏表单
    function hideForm() {
        elements.updateWasteRecordForm.style.display = 'none';
        elements.recordForm.reset();
    }

    // 处理表单提交
    async function handleFormSubmit(event) {
        event.preventDefault();

        const formData = {
            recordId: document.getElementById('recordId').value,
            residentId: document.getElementById('formResidentId').value,
            type: document.getElementById('type').value,
            time: document.getElementById('time').value,
            weight: document.getElementById('weight').value,
            location: document.getElementById('location').value,
            status: document.getElementById('status').value
        };

        // 验证表单
        if (!validateForm(formData)) {
            return;
        }

        try {
            showLoading(true);

            const response = await fetch(`${apiBaseUrl}/updateWasteRecord`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    recordId: Number(formData.recordId),
                    residentId: Number(formData.residentId),
                    type: formData.type,
                    time: formData.time,
                    weight: Number(formData.weight),
                    location: formData.location,
                    status: formData.status
                })
            });

            if (!response.ok) {
                throw new Error('修改失败');
            }

            showMessage('success', '修改成功！');
            hideForm();

            // 重新加载当前查询
            if (elements.queryResidentId.value) {
                await fetchWasteRecords();
            }
        } catch (error) {
            console.error('修改错误:', error);
            showMessage('error', '修改失败，请稍后再试！');
        } finally {
            showLoading(false);
        }
    }

    // 验证表单
    function validateForm(formData) {
        for (const key in formData) {
            if (!formData[key]) {
                showMessage('error', `请填写${getFieldName(key)}！`);
                return false;
            }
        }

        if (isNaN(formData.weight) || formData.weight <= 0) {
            showMessage('error', '请输入有效的重量值！');
            return false;
        }

        return true;
    }

    // 获取字段名称
    function getFieldName(key) {
        const names = {
            recordId: '记录编号',
            residentId: '居民编号',
            type: '垃圾类型',
            time: '投放时间',
            weight: '重量',
            location: '投放地点',
            status: '审核状态'
        };

        return names[key] || key;
    }

    // 初始化应用
    function initApp() {
        initEventListeners();
    }

    // 启动应用
    document.addEventListener('DOMContentLoaded', initApp);
</script>
</body>
</html>
